package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.*;

/**
 * 代码清单-p3ch13a-429页a：数字签名的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 18:42
 */
public class DigitalSignature {

    private static final Logger logger = LogManager.getLogger(DigitalSignature.class);

    public static void main(String[] args) throws SignatureException, InvalidKeyException {
        logger.info("...代码清单-p3ch13a-429页a：数字签名的使用示例...");

        DigitalSignature ds = new DigitalSignature();
        ds.testSignature();
    }

    private Signature signature;
    private PublicKey publicKey;
    private PrivateKey privateKey;
    private byte[] data = "Hello World".getBytes();

    public DigitalSignature() {
        init();
    }

    private void init() {
        try {
            signature = Signature.getInstance("SHA1withDSA");
            KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
            KeyPair keyPair = keyGenerator.generateKeyPair();

            publicKey = keyPair.getPublic();
            privateKey = keyPair.getPrivate();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public byte[] sign() throws InvalidKeyException, SignatureException {
        signature.initSign(privateKey);
        signature.update(data);
        return signature.sign();
    }

    public boolean verify(byte[] signatureData) throws InvalidKeyException, SignatureException {
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(signatureData);
    }

    public void testSignature() throws SignatureException, InvalidKeyException {
        boolean result = verify(sign());
        logger.info("...验证的结果：{}...", result);
    }



}
